package com.fc.mall.service.impl;

import com.fc.mall.dao.SmsHomeStatsDao;
import com.fc.mall.dto.*;
import com.fc.mall.dto.*;
import com.fc.mall.service.SmsHomeStatsService;
import org.joda.time.DateTime;
import org.joda.time.DateTimeConstants;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;

@Service
public class SmsHomeStatsServiceImpl implements SmsHomeStatsService {

    @Autowired
    private SmsHomeStatsDao smsHomeStatsDao;

    @Override
    public HomeStatsInfo getHomeStats() {
        DateTime startOfDay = DateTime.now().withTimeAtStartOfDay();
        DateTime startOfWeek = startOfDay.withDayOfWeek(DateTimeConstants.MONDAY);
        DateTime startOfMonth = startOfDay.withDayOfMonth(1);

        Date startOfDayDate = startOfDay.toDate();
        Date startOfWeekDate = startOfWeek.toDate();
        Date startOfMonthDate = startOfMonth.toDate();
        Date startOfYesterday = startOfDay.plusDays(-1).toDate();
        Date startOfRecentSevenDay = startOfDay.plusDays(-6).toDate();
        Date startOfLastWeek = startOfWeek.plusWeeks(-1).toDate();
        Date startOfLastMonth = startOfMonth.plusMonths(-1).toDate();

        HomeStatsInfo homeStatsInfo = new HomeStatsInfo();
        OrderSaleStatsInfo saleStatsInfo = smsHomeStatsDao.getOrderSaleStats(
                startOfDayDate,
                startOfYesterday,
                startOfRecentSevenDay);

        if (null == saleStatsInfo)
        {
            saleStatsInfo = OrderSaleStatsInfo.defaultValue();
        }
        homeStatsInfo.setOrderSaleStats(saleStatsInfo);

        OrderStatusStatsInfo statusStatsInfo = smsHomeStatsDao.getOrderStatusStats();
        if(null == saleStatsInfo)
        {
            statusStatsInfo = OrderStatusStatsInfo.defaultValue();
        }
        homeStatsInfo.setOrderStatusStats(statusStatsInfo);
        homeStatsInfo.setMemberStats(smsHomeStatsDao.getMemberStats(startOfDayDate, startOfYesterday, startOfMonthDate));
        homeStatsInfo.setProductStats(smsHomeStatsDao.getProductStats());
        OrderSaleSummaryStatsInfo summaryStatsInfo = smsHomeStatsDao.getOrderSaleSummaryStats(
                startOfWeekDate,
                startOfLastWeek,
                startOfMonthDate,
                startOfLastMonth);
        if(null == summaryStatsInfo)
        {
            summaryStatsInfo = OrderSaleSummaryStatsInfo.defaultValue();
        }
        homeStatsInfo.setOrderSaleSummaryStats(summaryStatsInfo);

        return homeStatsInfo;
    }

    @Override
    public List<OrderSalePerDayInfo> getOrderSaleOfPeriod(Date start, Date end) {
        return smsHomeStatsDao.getOrderSaleOfWeek(start, end);
    }
}
